package com.i72.penetrate.validate;


import com.i72.basic.consts.Consts;
import com.i72.penetrate.tools.HttpRequestHelper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class FormValidate implements RPCValidate {


    @Autowired
    private Validator validator;

    //@Autowired
    //private HttpRequestHelper httpRequestHelper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public boolean validate(Object o) {

        //ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        //Validator v = validatorFactory.getValidator();
        //v.validate(o);

        Set<ConstraintViolation<Object>>  error = validator.validate(o);

        StringBuilder stringBuilder = new StringBuilder();
        for(ConstraintViolation<Object> e:error){

            String value = e.getRootBeanClass().getName()+"."+e.getPropertyPath()+"字段"+e.getMessage();
            stringBuilder.append(value);
        }

        request.setAttribute(Consts.VALIDATE_FORM_ERROR_MESSAGE,stringBuilder.toString());

        if(error.size()>0) {
            return false;
        }


        return true;


    }

}
